﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Memcached.ClientLibrary;

namespace EmoneyWeiXinCommon
{
    public class MemcachedTools1 : IMemcachedCache
    {
        static string cacheName = "StockDoctor";



        static MemcachedTools1()
        {
            try
            {
                string servers = Config.MemServer;
                if (!string.IsNullOrEmpty(servers))
                {
                    String[] serverlist = servers.Split(',');
                    SockIOPool pool = SockIOPool.GetInstance(cacheName);
                    pool.SocketConnectTimeout = 5000000;
                    pool.SocketTimeout = 500000;
                    pool.SetServers(serverlist);
                    pool.Initialize();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        public MemcachedClient GetClient()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.PoolName = cacheName;
            mc.EnableCompression = false;
            return mc;
        }

        string GetKey(string key)
        {
            return Config.MemcachedKey + key;
        }

        public void Add(string key, object obj, int hours, int minutes, int seconds)
        {
            key = GetKey(key);
            MemcachedClient cache = GetClient();
            if (!cache.Add(key, obj, DateTime.Now.Add(new TimeSpan(hours, minutes, seconds))))
            {
                var result = cache.Set(key, obj, DateTime.Now.Add(new TimeSpan(hours, minutes, seconds)));
            }
        }

        public void Remove(string key)
        {
            key = GetKey(key);
            MemcachedClient cache = GetClient();
            cache.Delete(key);
        }

        public void FlushAll()
        {
            MemcachedClient cache = GetClient();
            cache.FlushAll();
        }

        public T Get<T>(string key)
        {
            key = GetKey(key);
            MemcachedClient cache = GetClient();
            try
            {
                return (T)cache.Get(key);
            }
            catch
            {
                return default(T);
            }
        }

        public object Get(string key)
        {
            key = GetKey(key);
            MemcachedClient cache = GetClient();
            try
            {
                return cache.Get(key);
            }
            catch (Exception ex)
            {
                StringTools.GetSendMail("key：" + key + " 获取缓存发生错误：" + ex);
                return null;
            }
        }
    }
}
